var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var commonLibs = require('../libs/commonLibs');
var underscore = require('underscore');
var http = require('http');
var https = require('https');
var querystring = require('querystring');
var Buffer = require('Buffer');
var Iconv = require('iconv-lite');
var req = require('request');



/* POST page. */
/*
 * {
 *      host: 'api.huimin100.cn',
 *      path: '/api',
 *      method: 'post',
 *      protocol: 'http',
 *      header_version: header携带的版本号,
 *      content_type: content_type,
 *      token: token,
 *      post_data: {
  *         'adminId': 123,
   *         'xxx': 111
  *     }
 */
router.post('/', function(req, res, next) {
    console.log("req.body", req.body);
    var time = new Date;
    var host = req.body.host;
    var path = req.body.path;
    var method = req.body.method ? req.body.method : 'get';
    var port = req.body.protocol === 'http' ? 80 : 443;
    var real_port = req.body.port ? req.body.port : '';
    var content_type = req.body.contentType ? req.body.contentType : 'application/x-www-form-urlencoded';
    var header_version = req.body.header_version ? req.body.header_version : '';
    var token = req.body.token ? req.body.token : '';
    var post_data = req.body.post_data;

    post_data = post_data ? post_data : {};

    post_data.ctime = time.getTime();
    post_data.nonce = crypto.randomBytes(13).toString("hex");
    post_data.client = post_data.client ? post_data.client : 11;
    post_data.version = post_data.version ? post_data.version : 100;
    post_data.code = '';
    post_data.sign = commonLibs.getSign(post_data);
    var options = {
        host: host,
        path: path,
        method: method
    };
    if(content_type !== 'application/json;charset=UTF-8'){
        options.headers = {
            'Content-Type': content_type,
            'Content-Length': querystring.stringify(post_data).length,
            'Accept': header_version,
            'Authorization': token
        }
    }else{
        options.headers = {
            'Content-Type': content_type,
            'Authorization': token
        }
    }
    var rq;
    if (port === 443){
        options.port = port;
        rq = https;
    }else {
        rq = http;
    }
    if(real_port){
        options.port = real_port;
    }

    var return_data = '';
    console.log("options", options);
    console.log("post_data", post_data);
    var reqst = rq.request(options, function(resp) {
        resp.setEncoding('utf8');
        resp.on('data', function(data) {
            return_data += data;
        });
        resp.on('end', function() {

            return_data = JSON.parse(JSON.stringify(return_data));
            console.log("return_data", return_data);
            // console.log(return_data)
            res.json(return_data);
        });

    });
    reqst.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });
    if(content_type === 'application/json;charset=UTF-8'){
        console.log("post_data json string:", JSON.stringify(post_data));
        reqst.write(JSON.stringify(post_data));
    }else{
        reqst.write(querystring.stringify(post_data));
    }
    reqst.end();
});

router.get('/export', function (req, res, next) {
    var time = new Date;
    var host = req.query.host;
    var path = req.query.path;
    var method = req.query.method ? req.query.method : 'get';
    var port = req.query.protocol == 'http' ? 80 : 443;
    var header_version = req.query.header_version ? req.query.header_version : '';
    var token = req.query.token ? req.query.token : '';
    var post_data = req.query.post_data;

    post_data = post_data ? post_data : {};

    post_data.ctime = time.getTime();
    post_data.nonce = crypto.randomBytes(13).toString("hex");
    post_data.client = post_data.client ? post_data.client : 11;
    post_data.version = post_data.version ? post_data.version : 100;
    post_data.code = '';
    post_data.sign = commonLibs.getSign(post_data);
    console.log(post_data);
    var options = {
        host: host,
        path: path,
        method: method,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': querystring.stringify(post_data).length,
            // 'Accept': header_version,
            'Authorization': token
        }
    };
    var rq;
    if (port == 443){
        options.port = port;
        rq = https;
    }else {
        rq = http;
    }

    var return_data = '';
    var reqst = rq.request(options, function(resp) {
        resp.setEncoding('binary');
        var type = resp.headers["content-type"];
        var filename = resp.headers["content-disposition"].split('=')[1];
        filename = Iconv.decode(filename, 'gb2312').toString();
        console.log(filename);
        resp.on('data', function(data) {
            return_data += data;
        });
        resp.on('end', function() {
            res.setHeader('Content-Disposition', 'attachment; filename='+encodeURIComponent(filename));
            res.setHeader('Content-Type', type);
            res.setHeader('transfer-encoding', 'chunked');
            res.setHeader('connection', 'close');
            res.write(return_data , "binary");
            res.end();
        });

    });
    reqst.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });
    reqst.write(querystring.stringify(post_data));
    reqst.end();
});

router.post('/upload', function (req, res, next) {
    console.log("req", req.headers)
    console.log("files", req.files)
});

module.exports = router;